import requests
import json
import pandas as pd
import time

API_KEY = "app-Faa07ZLJi0bnmgKe01B89Pbq"
BASE_URL = "http://8.136.111.93:8008/v1"


def generate_text(query, class_name, knowledge, type_param, difficulty, user="rzj", response_mode="streaming"):
    """
    通过在 query 中加入对话历史模拟“记忆”功能，
    将 conversation_history 中的所有回答拼接到 query 后面一起发送给 API。
    """
    url = f"{BASE_URL}/completion-messages"
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "inputs": {
            "query": query,  # 包含历史上下文
            "class_name": class_name,
            "knowledge": knowledge,
            "type": type_param,
            "difficulty": difficulty
        },
        "response_mode": response_mode,
        "user": user
    }

    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()  # 若状态码非200，会抛出异常
        print(f"response.json():{response.json()}")
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print("HTTP Error occurred:", http_err)
        print("Response Text:", response.text)
    except Exception as err:
        print("An error occurred:", err)
    return None


if __name__ == "__main__":
    # 业务参数
    class_name = "高等数学"
    knowledge = "微积分"
    type_param = "判断题"
    difficulty = "中等"

    # 对话轮次
    num_requests = 1

    # 对话“记忆”：保存所有历史生成的 answer
    conversation_history = ""

    # 存储多次请求的answer
    answers = []

    for i in range(num_requests):
        # 将已有对话记录拼接到 query 参数内，模拟记忆效果
        query_text = conversation_history.strip()

        # print(f"=== Request {i + 1} ===")
        # print(f"Query:\n{query_text if query_text else '(空)'}")

        result = generate_text(query_text, class_name,
                               knowledge, type_param, difficulty)

        if result:
            # 从返回结果中提取 answer
            answer = result.get("answer", "")
            answers.append(answer)
            # print(f"Answer {i + 1}:\n{answer}\n")

            # 更新对话历史，在下一次请求时带上
            conversation_history += "\n" + answer
        else:
            print("Request failed.\n")

        # 为防止请求过快，可以稍作延时
        time.sleep(1)

    # 将所有 answer 写入 Excel
    df = pd.DataFrame([
        {"request_id": i + 1, "answer": ans}
        for i, ans in enumerate(answers)
    ])
    excel_file = "api_answers.xlsx"
    df.to_excel(excel_file, index=False)
    print(f"所有生成的答案已写入：{excel_file}")
